package com.cloud.core.redis;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import redis.clients.jedis.Jedis;

/**
 * 1Cloud1
 * @author Administrator
 * @since 2015-11-4
 * @version 1.0 
 */
@Component("RedisClient")
public class RedisClient {
	@Autowired
	private RedisFactory RedisFactory;
	
	/**
	 * 保存二进制
	 * @param key
	 * @param bytes
	 * @param valid
	 */
	public void setBytes(String key, byte[] bytes, int valid) {
		Jedis jedis = RedisFactory.getInstance();
		try {
			if(valid != -1)
				jedis.setex(key.getBytes(), valid, bytes);
			else 
				jedis.set(key.getBytes(), bytes);
		} catch (Exception e) {
			RedisFactory.returnBrokenResource(jedis);
		} finally {
			RedisFactory.returnResource(jedis);
		}
	}
	
	/**
	 * 保存字符串
	 * @param key
	 * @param value
	 * @param valid
	 */
	public void setString(String key, String value, int valid) {
		Jedis jedis = RedisFactory.getInstance();
		try {
			if(valid != -1)
				jedis.setex(key, valid, value);
			else 
				jedis.set(key, value);
		} catch (Exception e) {
			RedisFactory.returnBrokenResource(jedis);
		} finally {
			RedisFactory.returnResource(jedis);
		}
	}
	
	/**
	 * 保存列表
	 * @param key
	 * @param value
	 * @param valid
	 */
	public void rpush(String key, String value, int valid) {
		Jedis jedis = RedisFactory.getInstance();
		try {
			jedis.rpush(key, value);
			if(valid != -1)
				jedis.expire(key, valid);
		} catch (Exception e) {
			RedisFactory.returnBrokenResource(jedis);
		} finally {
			RedisFactory.returnResource(jedis);
		}
	}
	
	/**
	 * 获取列表
	 * @param key
	 */
	public List<String> lrange(String key) {
		Jedis jedis = RedisFactory.getInstance();
		List<String> indexList = new ArrayList<String>();
		try {
			indexList = jedis.lrange(key, 0, -1);
		} catch (Exception e) {
			RedisFactory.returnBrokenResource(jedis);
		} finally {
			RedisFactory.returnResource(jedis);
		}
		return indexList;
	}
	
	/**
	 * 获取字符串
	 * @param key
	 */
	public String get(String key) {
		Jedis jedis = RedisFactory.getInstance();
		try {
			return jedis.get(key);
		} catch (Exception e) {
			RedisFactory.returnBrokenResource(jedis);
		} finally {
			RedisFactory.returnResource(jedis);
		}
		return null;
	}
	
	/**
	 * 删除
	 * @param key
	 */
	public void del(String key) {
		Jedis jedis = RedisFactory.getInstance();
		try {
			jedis.del(key);
		} catch (Exception e) {
			RedisFactory.returnBrokenResource(jedis);
		} finally {
			RedisFactory.returnResource(jedis);
		}
	}
	
	/**
	 * 是否存在
	 * @param key
	 * @return
	 */
	public boolean exists(Object key){
		Jedis jedis = RedisFactory.getInstance();
		try {
			if(key instanceof String)
				return jedis.exists((String)key);
			if(key instanceof byte[])
				return jedis.exists((byte[])key);
		} catch (Exception e) {
			RedisFactory.returnBrokenResource(jedis);
		} finally {
			RedisFactory.returnResource(jedis);
		}
		return false;
	}
}